package com.sscaipiao.android.activity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.sscaipiao.android.R;
import com.sscaipiao.android.common.Constants;
import com.sscaipiao.android.model.User;
import com.sscaipiao.android.utils.StringUtil;
import com.sscaipiao.android.utils.UserDataServiceHelper;

public class RegistBankBindActivity extends Activity implements
		OnClickListener, TextWatcher {

	private Button backButton;
	private Button finishButton;

	private EditText edit_text_regist_bank_bind_card_num;

	private Spinner regist_bank_bind_spinner_bank;
	private Spinner regist_bank_bind_spinner_province;
	private Spinner regist_bank_bind_spinner_city;
	private AutoCompleteTextView regist_bank_bind_autoComplete_branch;

	private LinearLayout regist_bank_bind_hidden_layout;

	private TextView regist_bank_bind_txt_already_bind_number;

	private User user;

	private ArrayAdapter<String> bankAdapter;
	private ArrayAdapter<String> provinceAdapter;
	private ArrayAdapter<String> cityAdapter;

	public String[] provinces = null;

	private String[] items = {};

	private int formerBankSeq = 0;
	private int formerProvinceSeq = 0;
	private int formerCitySeq = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
				.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
				.penaltyLog().penaltyDeath().build());

		super.onCreate(savedInstanceState);
		setContentView(R.layout.regist_bank_bind);

		Intent i = this.getIntent();
		if (!i.equals(null)) {
			Bundle b = i.getExtras();
			if (b != null) {
				if (b.containsKey(Constants.USER)) {
					user = (User) b.get(Constants.USER);
				}
			}
		}

		regist_bank_bind_spinner_bank = (Spinner) findViewById(R.id.regist_bank_bind_spinner_bank);
		regist_bank_bind_spinner_province = (Spinner) findViewById(R.id.regist_bank_bind_spinner_province);
		regist_bank_bind_spinner_city = (Spinner) findViewById(R.id.regist_bank_bind_spinner_city);
		regist_bank_bind_autoComplete_branch = (AutoCompleteTextView) findViewById(R.id.regist_bank_bind_autoCompleteTextView);
		regist_bank_bind_autoComplete_branch
				.setAdapter(new ArrayAdapter<String>(this,
						android.R.layout.simple_dropdown_item_1line, items));
		regist_bank_bind_autoComplete_branch.addTextChangedListener(this);
		// // 将可选内容与ArrayAdapter连接起来
		// ArrayAdapter sortAdapter = ArrayAdapter.createFromResource(this,
		// R.array.sort, android.R.layout.simple_spinner_item);
		// ArrayAdapter groupAdapter = ArrayAdapter.createFromResource(this,
		// R.array.group, android.R.layout.simple_spinner_item);
		//
		// // 设置下拉列表的风格
		// sortAdapter
		// .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// groupAdapter
		// .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		//
		// // 将adapter 添加到spinner中
		// sortSpinner.setAdapter(sortAdapter);
		// groupSpinner.setAdapter(groupAdapter);

		String bankJson = UserDataServiceHelper.getBank(
				RegistBankBindActivity.this, user);
		Log.v("bankJson", bankJson);
		bankJson = bankJson.substring(bankJson.indexOf("["));
		String provineJson = UserDataServiceHelper.getProvince(
				RegistBankBindActivity.this, user);
		Log.v("provineJson", provineJson);
		provineJson = provineJson.substring(provineJson.indexOf("["));



		String[] banks = null;

		JSONArray jsonArray = null;
		try {
			jsonArray = new JSONArray(bankJson);
			banks = new String[jsonArray.length() + 1];
			banks[0] = "请选择";
			for (int j = 0; j < jsonArray.length(); j++) {
				banks[j + 1] = jsonArray.getString(j);
				if (StringUtil.isNotEmptyString(user.getBank())
						&& user.getBank().equals(jsonArray.getString(j))) {
					formerBankSeq = j + 1;
				}
			}

			jsonArray = new JSONArray(provineJson);
			provinces = new String[jsonArray.length() + 1];
			provinces[0] = "请选择";
			for (int j = 0; j < jsonArray.length(); j++) {
				provinces[j + 1] = jsonArray.getString(j);
				if (StringUtil.isNotEmptyString(user.getProvince())
						&& user.getProvince().equals(jsonArray.getString(j))) {
					formerProvinceSeq = j + 1;
					getCityFromProvince(user.getProvince(), user.getCity());
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		bankAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, banks);
		provinceAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, provinces);
		cityAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, new String[] { "请选择" });

		// 设置下拉列表的风格
		bankAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		provinceAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		cityAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// 将adapter 添加到spinner中
		regist_bank_bind_spinner_bank.setAdapter(bankAdapter);
		regist_bank_bind_spinner_province.setAdapter(provinceAdapter);
		regist_bank_bind_spinner_city.setAdapter(cityAdapter);
		// 添加事件Spinner事件监听
		regist_bank_bind_spinner_bank
				.setOnItemSelectedListener(new SpinnerSelectedListener());
		regist_bank_bind_spinner_province
				.setOnItemSelectedListener(new SpinnerProvinceSelectedListener());
		regist_bank_bind_spinner_city
				.setOnItemSelectedListener(new SpinnerSelectedListener());
		// 设置默认值
		regist_bank_bind_spinner_bank.setVisibility(View.VISIBLE);
		//regist_bank_bind_spinner_bank.setSelection(formerBankSeq);
		regist_bank_bind_spinner_province.setVisibility(View.VISIBLE);
		//regist_bank_bind_spinner_province.setSelection(formerProvinceSeq);
		regist_bank_bind_spinner_city.setVisibility(View.VISIBLE);
		//regist_bank_bind_spinner_city.setSelection(formerCitySeq);
		


		backButton = (Button) findViewById(R.id.regist_bank_bind_button_back);
		finishButton = (Button) findViewById(R.id.regist_bank_bind_finish);

		regist_bank_bind_hidden_layout = (LinearLayout) findViewById(R.id.regist_bank_bind_hidden_layout);
		regist_bank_bind_txt_already_bind_number = (TextView) findViewById(R.id.regist_bank_bind_txt_already_bind_number);

		edit_text_regist_bank_bind_card_num = (EditText) findViewById(R.id.edit_text_regist_bank_bind_card_num);

		if (user != null && StringUtil.isNotEmptyString(user.getBankno())) {
			regist_bank_bind_hidden_layout.setVisibility(View.VISIBLE);
			regist_bank_bind_txt_already_bind_number.setText(user.getBankno()
					.substring(0, 4)
					+ " **** **** "
					+ user.getBankno().substring(user.getBankno().length() - 4,
							user.getBankno().length()));

		} else {
			regist_bank_bind_hidden_layout.setVisibility(View.GONE);
		}

		backButton.setOnClickListener(this);
		finishButton.setOnClickListener(this);
		

	}

	@Override
	public void onClick(View v) {
		if (R.id.regist_bank_bind_button_back == v.getId()) {

			// Intent intent = new Intent(RegistBankBindActivity.this,
			// Regist2Activity.class);
			// Bundle b = new Bundle();
			// b.putSerializable(Constants.USER, user);
			// intent.putExtras(b);
			// startActivity(intent);
			RegistBankBindActivity.this.finish();
		} else if (R.id.regist_bank_bind_finish == v.getId()) {

			String pleaseChoose = "请选择";
			
			//Log.v("regist_bank_bind_spinner_bank", regist_bank_bind_spinner_bank.getSelectedItem().toString());
			//Log.v("regist_bank_bind_spinner_bank", regist_bank_bind_spinner_bank.getSelectedItemPosition()+ "");
			
			if (regist_bank_bind_spinner_bank.getSelectedItem().toString() != null
					&& regist_bank_bind_spinner_bank.getSelectedItem()
							.toString().equals(pleaseChoose)) {
				Toast.makeText(RegistBankBindActivity.this, "请选择银行",
						Toast.LENGTH_SHORT).show();
				return;
			} else if (regist_bank_bind_spinner_province.getSelectedItem()
					.toString() != null
					&& regist_bank_bind_spinner_province.getSelectedItem()
							.toString().equals(pleaseChoose)) {
				Toast.makeText(RegistBankBindActivity.this, "请银行所在省",
						Toast.LENGTH_SHORT).show();
				return;
			} else if (regist_bank_bind_spinner_city.getSelectedItem()
					.toString() != null
					&& regist_bank_bind_spinner_city.getSelectedItem()
							.toString().equals(pleaseChoose)) {
				Toast.makeText(RegistBankBindActivity.this, "请银行所在市",
						Toast.LENGTH_SHORT).show();
				return;
			} else if (regist_bank_bind_autoComplete_branch.getText()
					.toString() != null
					&& StringUtil
							.isEmptyString(regist_bank_bind_autoComplete_branch
									.getText().toString())) {
				Toast.makeText(RegistBankBindActivity.this, "请填写支行名称",
						Toast.LENGTH_SHORT).show();
				return;
			} else if (edit_text_regist_bank_bind_card_num.getText().toString() != null
					&& StringUtil
							.isEmptyString(edit_text_regist_bank_bind_card_num
									.getText().toString())) {
				Toast.makeText(RegistBankBindActivity.this, "请填写银行卡号",
						Toast.LENGTH_SHORT).show();
				return;
			}

			user.setBank(regist_bank_bind_spinner_bank.getSelectedItem()
					.toString());
			user.setBankFullName(regist_bank_bind_autoComplete_branch.getText()
					.toString());
			user.setBankno(edit_text_regist_bank_bind_card_num.getText()
					.toString());

			UserDataServiceHelper.saveBankInfo(RegistBankBindActivity.this,
					user, regist_bank_bind_spinner_province.getSelectedItem()
							.toString(), regist_bank_bind_spinner_city
							.getSelectedItem().toString());

			Intent intent = new Intent(RegistBankBindActivity.this,
					Regist2Activity.class);
			Bundle b = new Bundle();
			b.putSerializable(Constants.USER, user);
			intent.putExtras(b);
			startActivity(intent);
		}

	}

	class SpinnerSelectedListener implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				final int arg2, long arg3) {

		}

		public void onNothingSelected(AdapterView<?> arg0) {

		}
	}

	class SpinnerProvinceSelectedListener implements OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				final int arg2, long arg3) {
			Log.v("SpinnerProvinceSelectedListener", arg3 + "");
			if (arg3 != 0) {
				String provinceName = provinces[(int) arg3];
				getCityFromProvince(provinceName, "");
			}

		}

		public void onNothingSelected(AdapterView<?> arg0) {

		}
	}

	/**
	 * @param provinceName
	 */
	private void getCityFromProvince(String provinceName, String cityName) {
		String cityJson = UserDataServiceHelper.getCity(
				RegistBankBindActivity.this, provinceName, user);
		cityJson = cityJson.substring(cityJson.indexOf("["));

		String[] citis = null;

		JSONArray jsonArray = null;
		try {

			jsonArray = new JSONArray(cityJson);
			citis = new String[jsonArray.length() + 1];
			citis[0] = "请选择";
			for (int j = 0; j < jsonArray.length(); j++) {
				citis[j + 1] = jsonArray.getString(j);
				if (StringUtil.isNotEmptyString(cityName)
						&& cityName.equals(jsonArray.getString(j))) {
					formerCitySeq = j + 1;
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		cityAdapter = new ArrayAdapter<String>(RegistBankBindActivity.this,
				android.R.layout.simple_spinner_item, citis);
		cityAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// 将adapter 添加到spinner中
		regist_bank_bind_spinner_city.setAdapter(cityAdapter);
	}

	/*
	 * 步骤2.2，TextWatcher将需实现afterTextChanged(),beforeTextChanged(),onTextChanged(
	 * )三个方法。本例无须处理after和before，之针对onTextChanged进行处理
	 */
	public void afterTextChanged(Editable s) {
		if (regist_bank_bind_autoComplete_branch.getText() != null
				&& !StringUtil
						.isEmptyString(regist_bank_bind_autoComplete_branch
								.getText().toString())
				&& regist_bank_bind_autoComplete_branch.getText().toString()
						.length() % 3 == 0) {
			Log.v("afterTextChanged", regist_bank_bind_spinner_bank
					.getSelectedItem().toString());
			String subBankJson = UserDataServiceHelper.getSubBank(
					RegistBankBindActivity.this, regist_bank_bind_spinner_bank
							.getSelectedItem().toString(),
					regist_bank_bind_autoComplete_branch.getText().toString(),
					user);

			Log.v("subBankJson", subBankJson);
			subBankJson = subBankJson.substring(subBankJson.indexOf("["));
			// subBankJson = "[\"123华夏银行乌鲁木齐长江路支行\",\"华夏银行沈123阳分行长江支行\"]";
			JSONArray jsonArray = null;
			try {
				jsonArray = new JSONArray(subBankJson);
				items = new String[jsonArray.length()];
				for (int j = 0; j < jsonArray.length(); j++) {
					items[j] = jsonArray.getString(j);
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
			if (items != null && items.length > 0)
				Log.v("items", items[0]);
			regist_bank_bind_autoComplete_branch
					.setAdapter(new ArrayAdapter<String>(this,
							android.R.layout.simple_dropdown_item_1line, items));

		}
	}

	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// nothing to do
	}

	public void onTextChanged(CharSequence s, int start, int before, int count) {
	}

}
